package com.atxiao.service.JUC;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Share2{
    private int number=0;

    private Lock myLock=new ReentrantLock();

    private Condition condition=myLock.newCondition();
    public void incr() throws InterruptedException {
        //判断
        try {
            myLock.lock();
            while (number!=0){
            condition.await();
            }
            //干活
            number++;
            System.out.println(Thread.currentThread().getName()+":"+number);
            //唤醒其他线程
            condition.signalAll();
        }finally {
            myLock.unlock();
            //通知
        }
    }

    public void decr() throws InterruptedException{

        try {

            myLock.lock();
            while (number!=1){
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName()+":"+number);
            condition.signalAll();
        }finally {
            myLock.unlock();
        }
    }


}


public class ThreadNotice2 {
    public static void main(String[] args) {
        Share2 share2 = new Share2();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    share2.incr();
                } catch (InterruptedException e) {
                }
            }
        },"AA").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    share2.decr();
                } catch (InterruptedException e) {
                }
            }
        },"BB").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    share2.incr();
                } catch (InterruptedException e) {
                }
            }
        },"CC").start();
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                try {
                    share2.decr();
                } catch (InterruptedException e) {
                }
            }
        },"DD").start();
    }



}
